﻿using Microsoft.EntityFrameworkCore;
using TuLing.Dto;
using TuLing.Entities;
using TuLing.IServices;

namespace TuLing.Services
{
    public class ProductCategoryService : BaseService, IProductCategoryService
    {
        public ProductCategoryService(DefaultDbContext context) : base(context) { }

        /// <summary>
        /// 检索分类
        /// </summary>
        public async Task<List<ProductCategoryDto>> SearchProductType(string keyword)
        {
            if (keyword == null)
            {
                var list = await _context.ProductCategorys.ToListAsync();
                return list.Select(u => new ProductCategoryDto
                {
                    Id = u.Id,
                    Code = u.Code,
                    Name = u.Name,
                    ParentId = u.ParentId
                }).ToList();
            }
            else 
            {             
                var list = await _context.ProductCategorys.Where(m => m.Name.Contains(keyword)).ToListAsync();
                return list.Select(u => new ProductCategoryDto
                {
                    Id = u.Id,
                    Code = u.Code,
                    Name = u.Name,
                    ParentId = u.ParentId
                }).ToList();
            }
        }

        /// <summary>
        /// 获取分类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ProductCategoryDto?> Get(long id)
        {
            var first = await _context.ProductCategorys.Include(s=>s.Children).FirstOrDefaultAsync(m => m.Id == id);
            
            if (first == null)
            {
                return null;
            }

            return new ProductCategoryDto
            {
                Id = first.Id,
                Code = first.Code,
                Name = first.Name,
                ParentId = first.ParentId,
                Children = first.Children.Select(c => new ProductCategoryDto
                {
                    Id = c.Id,
                    Code = c.Code,
                    Name = c.Name,
                    ParentId = c.ParentId
                }).ToList()
            };
        }

        /// <summary>
        /// 分类树
        /// </summary>
        /// <returns></returns>
        public async Task<List<ProductCategoryDto>> GetTree()
        {
            var list = await _context.ProductCategorys.ToListAsync();
            var listDto = list.Select(u =>
            new ProductCategoryDto()
            {
                Id = u.Id,
                Code = u.Code,
                Name = u.Name,
                ParentId = u.ParentId
            }).ToList();
            return BuildTree(listDto);
        }

        private List<ProductCategoryDto> BuildTree(List<ProductCategoryDto> allNodes)
        {
            var rootNodes = new List<ProductCategoryDto>();
            // 构建节点字典，方便查找
            var nodeDict = new Dictionary<long, ProductCategoryDto>();

            foreach (var node in allNodes)
            {
                nodeDict[node.Id] = node;
            }

            foreach (var node in allNodes)
            {
                if (node.ParentId == 0)
                    // 根节点
                    rootNodes.Add(node);
                else if (nodeDict.TryGetValue(node.ParentId, out var parent))
                {
                    // 找到父节点并添加子节点
                    parent.Children.Add(node);
                }
            }
            return rootNodes;
        }
       
        /// <summary>
        /// 检查分类是否存在
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> IsExist(ProductCategoryDto input)
        {
            return await _context.ProductCategorys.AnyAsync(m => m.Name.Equals(input.Name) && m.Id != input.Id);
        }

        /// <summary>
        /// 保存分类
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task Save(ProductCategoryDto input)
        {
            if (input.Id > 0)
            {
                var category = await _context.ProductCategorys.FirstOrDefaultAsync(m => m.Id == input.Id);
                if (category == null)
                {
                    throw new Exception("商品分类不存在。");
                }
                category.Name = input.Name;
                category.Code = input.Code;
                category.ParentId = input.ParentId;

                _context.ProductCategorys.Update(category);
                await _context.SaveChangesAsync();
            }
            else
            {
                if (await _context.ProductCategorys.AnyAsync(m => m.Name.Equals(input.Name)))
                {
                    throw new Exception("商品分类已存在。");
                }
                if (input.ParentId <= 0)
                {
                    input.ParentId = 0; // 确保根节点的 ParentId 为 0
                }
                var category = new ProductCategory
                {
                    Name = input.Name,
                    Code = input.Code,
                    ParentId = input.ParentId
                };                
                _context.ProductCategorys.Add(category);
                await _context.SaveChangesAsync();
            }
        }

        /// <summary>
        /// 删除分类
        /// </summary>  
        public async Task Delete(long id)
        {
            var pType = await _context.ProductCategorys.FirstOrDefaultAsync(m => m.Id == id);
            if (pType == null)
            {
                throw new Exception("商品分类不存在。");
            }
            else
            {
                _context.ProductCategorys.Remove(pType);
                _context.SaveChanges();
            }
        }

    }
}
